import { ScoreBoardDataBase } from "sapi-pro";

export interface ElevatorCatConfig {
    /**声明条数 */
    lives: number; // 生命条数
    /**游戏时长 */
    time: number; // 游戏时长
    /**指南针冷却 */
    locateCooldown: number;
    locateCooldownCat: number; // 猫猫指南针冷却
    attackCooldown: number; // 攻击后停顿
    bellMode: boolean; // 盗铃模式
}

class ElevatorCatConfigManager {
    private readonly db = new ScoreBoardDataBase("elevator", undefined, false);
    private defaultConfig: ElevatorCatConfig = {
        lives: 3,
        time: 60,
        locateCooldown: 10,
        locateCooldownCat: 15,
        attackCooldown: 1,
        bellMode: false,
    };

    // 获取配置，自动应用默认值
    getConfig(): ElevatorCatConfig {
        const parsePositiveInt = (v: unknown, fallback: number) => {
            const n = parseInt(String(v), 10);
            return Number.isFinite(n) && n > 0 ? n : fallback;
        };

        return {
            lives: parsePositiveInt(this.db.get("health"), this.defaultConfig.lives),
            time: parsePositiveInt(this.db.get("time"), this.defaultConfig.time),
            locateCooldown: parsePositiveInt(
                this.db.get("compass"),
                this.defaultConfig.locateCooldown
            ),
            locateCooldownCat: parsePositiveInt(
                this.db.get("compasscat"),
                this.defaultConfig.locateCooldownCat
            ),
            attackCooldown: parsePositiveInt(
                this.db.get("attack"),
                this.defaultConfig.attackCooldown
            ),
            bellMode: Boolean(this.db.get("dl") ?? this.defaultConfig.bellMode),
        };
    }

    // 保存配置到 db
    setConfig(config: Partial<ElevatorCatConfig>) {
        if (config.lives !== undefined) this.db.set("health", config.lives);
        if (config.time !== undefined) this.db.set("time", config.time);
        if (config.locateCooldown !== undefined) this.db.set("compass", config.locateCooldown);
        if (config.locateCooldownCat !== undefined)
            this.db.set("compasscat", config.locateCooldownCat);
        if (config.attackCooldown !== undefined) this.db.set("attack", config.attackCooldown);
        if (config.bellMode !== undefined) this.db.set("dl", Number(config.bellMode));
    }

    // 获取默认配置
    getDefaultConfig(): ElevatorCatConfig {
        return { ...this.defaultConfig };
    }
}

export const eleConfigManager = new ElevatorCatConfigManager();
